<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/24
 * Time: 11:45
 */

namespace app\adminapi\controller;

use app\adminapi\model\User;
use app\base\service\Redis;
use think\Controller;
use think\Config;
use think\Request;
use think\Validate;
class Base extends \app\base\controller\Base
{
    public $uid;
    public $redis;
    public $token;
    public $requestMethod;
    public $dateTime;
    public $appId;

    protected $session = [];

    /**
     * 初始化 redis 请求
     */
    public function _initialize()
    {
        // 验证用户是否登录，以及是否有权限进行操作
        $this->session = ( new User() )->checkAuth();

        $redisServer    = Redis::getInstance();
        $this->redis    = $redisServer->redis;
        //$this->redis->connect(Config::get('redis.host'), Config::get('redis.port'));
        $this->token    = input('token','');
        $this->requestMethod = Request::instance()->isPost(); //测试期间允许GET方便测试
        $this->dateTime = date('Y-m-d H:i:s');
        $this->uid      = input('uid');
        if(Request::instance()->isOptions()){
            $this->cos();
            exit();
        }
    }

    public function setRedis($key,$value){
        $data = is_array($value) ? serialize($value) : $value;
        $this->redis->set($key,$data);
    }

    public function getRedis($key){
        $value    = $this->redis->get($key);
        $jsonData = unserialize($value);
        return (null === $jsonData) ? $value : $jsonData;
    }

    public function cos(){
        header("Access-Control-Allow-Origin: * ");
        header("Access-Control-Allow-Methods: GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Headers: content-type,user-token");
        header("Access-Control-Max-Age: 2592000");
    }

    /**
     * 成功返回
     */
    public function retSucc($data=array(),$msg='ok',$code=1){
        $this->cos();
        $info['code'] = $code;
        $info['msg']  = $msg;
        $info['time'] = time();
        if(is_array($data)){
            $info         = array_merge($info,$data);
        }else{
            $info['data'] = $data;
        }
        return json($info);
    }

    /**
     * 失败返回
     */
    public function retError($msg='',$code=0){
        $this->cos();
        $info['code'] = $code;
        $info['msg']  = intval($msg)>99 ? $this->getErrorMsg($msg) : $msg;
        $info['time'] = time();
        return json($info);
    }

	public function retAll($msg='',$type=0){
        if($msg){
            if(is_array($msg)){
                if($type==0){
                    return $this->retSucc(['data' =>$msg]);
                }else{
                    return $this->retSucc($msg);
                }
            }else{
                return $this->retSucc();
            }
        }else{
            return $this->retError($msg);
        }
    }
    /**
     * 错误信息代码转换
     * @param int $code
     * @return string
     */
    public function getErrorMsg($code=100){
        Config::set(include  APP_PATH.'/../config/api/config.php','api');
        $errorArr = Config::get('api.error_msg');
        return isset($errorArr[$code]) ? $errorArr[$code] : $code;
    }

    /**
     * @return mixed|\think\response\Json
     */
    public function _empty(){
        return $this->retAll([]);
    }
    /**
     * 变量批量获取 及 校验变量
     * @param string $string
     * @param string $method
     * @return array
     */
    public function getBatchParam($string='',$method=''){
        // order_id|1|oid#订单id@require|email/order_no#单号@require|email
        $data = [];
        $arr  = explode('/',$string);
        $rule = [];
        foreach ($arr as $v){
            $ruleArr        = explode('#',$v);
            $arr1           = explode('|',$ruleArr[0]);
            $name           = ($arr1[2] && $arr1[2]<>'-') ? $arr1[2] : $arr1[0];
            if(isset($ruleArr[1])){
                $holeName = explode('@',$ruleArr[1]);
                if(isset($holeName[1])){
                    $rule[$name.'|'.$holeName[0]] = $holeName[1];
                }else{
                    $rule[$name] = $holeName[0];
                }
            }
            $method         = ($arr1[3] && $arr1[3]<>'-') ? $arr1[3].'.' : $method.'.';
            $vari           = ($arr1[3] && $arr1[3]<>'-') ? $arr1[3].'.'.$arr1[0] : $arr1[0];
            $data[$name]    = isset($arr1[1]) ? input($vari,$arr1[1]) : input($vari);
        }
        if(!empty($rule)){
            $validate = new Validate($rule);
            if (!$validate->batch()->check($data)) {
                $checkMsg = $validate->getError();
                if(is_array($validate->getError())){
                    $arr = [];
                    foreach ($checkMsg as $k=>$v){
                        $arr[] = $v;
                    }
                    $checkMsg = implode(',',$arr);
                }
                abort(0,$this->getErrorMsg($checkMsg));//$this->requestStatus
            }
        }
        return $data;
    }
}